package netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.ScheduledFuture;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

public class EchoClient {

	private final String host;
	private final int port;
	
	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}
	
	public void start() throws InterruptedException{
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group)
			 .channel(NioSocketChannel.class)
			 .remoteAddress(new InetSocketAddress(host, port))
			 .handler(new ChannelInitializer<SocketChannel>() {
				protected void initChannel(SocketChannel ch) throws Exception {
					System.out.println("client init");
					ch.pipeline().addLast(new EchoClientHandler());
				}
			});
			ChannelFuture f = bootstrap.connect().sync();
//			f.addListener(new GenericFutureListener<Future<? super Void>>() {
//                public void operationComplete(Future<? super Void> future) throws Exception {
//                    System.out.println("operationComplete:" + future.get());
//                }
//            });
            Channel channel = f.channel();
            ChannelFuture channelFuture = channel.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
            channelFuture.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("channel success");
                    } else {
                        future.cause().printStackTrace();
                    }
                }
            });
            ScheduledFuture<?> scheduledFuture = channel.eventLoop().scheduleAtFixedRate(() -> {
                channel.writeAndFlush(Unpooled.copiedBuffer("hello world".getBytes()));
            }, 1, 1, TimeUnit.SECONDS);
            Thread.sleep(10000);
            scheduledFuture.cancel(true);
            channel.closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		new EchoClient("0:0:0:0:0:0:0:0", 8888).start();
	}
}

